import re
from stl import mesh
import numpy as np

def extract_info_from_stl_filename(file_name_lists, grain_index: int) -> dict:
    # 提取STL文件名称中的信息
    # 根据grain_index查找开头为0#，1#，2#的文件名
    file_title = f"{grain_index}#"
    stl_full_name = next(
        (file_name for file_name in file_name_lists if (file_name.startswith(file_title) and file_name.endswith("BS.stl"))), None)
    # 使用正则表达式提取数字，以0#N6L3215M20BS为例子，n_slots=6，lz=3.215，m=2.0
    numbers = re.findall(r'\d+', stl_full_name)
    n_slots = int(numbers[1])
    lz = int(numbers[2])/1000.0
    m=int(numbers[3])/10.0
    return {"grain_index": grain_index,
            "n_slots": n_slots,
            "lz": lz,
            "m": m,
            "stl_full_name": stl_full_name,
            "cr_txt_full_name": stl_full_name.replace("BS.stl", "CR.txt"),
            "sr_txt_full_name": stl_full_name.replace("BS.stl", "SR.txt")}


def read_stl_by_given_point_num(file_path : str, total_points:int=5000):
    # 读取STL文件
    burning_surface_mesh = mesh.Mesh.from_file(file_path)
    # 获取三角形的总数
    num_triangles = len(burning_surface_mesh.vectors)
    random_array = np.random.randint(low=0, high=num_triangles, size=total_points)
    # 存储所有点坐标的集合
    vertices=np.array([])
    for index in random_array:
        triangle = burning_surface_mesh.vectors[index]
        # 获取三角形的三个顶点
        v0, v1, v2 = triangle
        new_point = generate_random_point_in_triangle(v0, v1, v2)
        # 将新点坐标添加到集合中
        vertices=np.append(vertices,new_point)
    # 将一维数组转换为二维数组
    vertices = vertices.reshape(-1, 3)
    # 将数组元素类型转换为 float32
    vertices = vertices.astype(np.float32)
    # 返回NumPy数组
    return vertices

# 在三角形内随机生成点
def generate_random_point_in_triangle(v0, v1, v2):
    while True:
        u1,u2=np.random.random(2)
        if u1+u2> 1:
            continue
        break
    # 计算新点的坐标
    p = v0+ u1*(v1-v0) + u2*(v2-v0)
    return p
